import React,{useState,useEffect} from "react";
import { Pie } from '@ant-design/charts';
import { DatePicker } from 'antd';
import dayjs from 'dayjs'; //引入dayjs
const fommatData=(list)=>{
    let obj ={}
    list.forEach(item=>{
        if(obj[item.leave1]){
            let price = obj[item.leave1]
            let price2 = price+ Number(item.price)
            obj[item.leave1]=Number(price2.toFixed(2))
        }else{
            obj[item.leave1]=Number(item.price)
        }
    })

    let objList=[]
    for(var key in obj){
        let res={}
        res.label=key
        res.value=obj[key]
        objList.push(res)
    }
    console.log(objList)
    return objList
}
const PieCharts = (props) => {
  let defaultValue = dayjs().format('YYYY-MM'); // 当前时间
  const {list} = props;
  const [selectedMonth, setSelectedMonth] = useState(defaultValue); // 选择的月份
  const [chartData, setChartData] = useState([]); // 图表数据
  const config = {
      description: {
        visible: true,
        text:'饼图',
      },
      radius: 0.8,
      data:chartData,
      angleField: 'value',
      colorField: 'label',
  };
  useEffect(()=>{
    console.log('pieuseEffect')
    let timeData = list.filter(item=>item.time.slice(0,7) === selectedMonth)
    setChartData(fommatData(timeData))
      console.log(fommatData(timeData))
  },[selectedMonth,list])
  const onChange = (date, dateString) => {
    defaultValue = dateString
    setSelectedMonth(dateString);
  };
  return (
    <div className="charts-box">
       <div className='charts-header'>月份<DatePicker onChange={onChange} picker="month" defaultValue={dayjs(defaultValue, 'YYYY-MM')} /></div>
        <div className='charts-item'>
          <Pie {...config} />
        </div>
     </div> 
  )
}
export default PieCharts